import { defineComponent, h, onMounted, onUnmounted, ref } from '@vue/runtime-core'
import { hitTestObject } from '../utils'
import { game } from '../Game'
import Map from '../components/map/Map'
import Plane from '../components/plane/Plane'
import Enemy from '../components/enemy/Enemy'
import Bullet from '../components/bullet/Bullet'
import Integral from '../components/integral/Integral'
import { usePlaneMove } from '../components/plane/usePlaneMove'
import { useEnemyPlane } from '../components/enemy/useEnemyPlane'
import { useBullet } from '../components/bullet/useBullet'
import { getScreenSize } from '../utils'
export default defineComponent({
  setup(props, ctx) {
    const { height: screenHeight } = getScreenSize()
    const { planeInfo } = usePlaneMove()
    const { enemyPlans } = useEnemyPlane()
    const { bullets } = useBullet(planeInfo)
    const bulletSpeed = 5
    const integralNum = ref(0)
    const handleTicker = () => {
      // 我方飞机和敌方飞机撞击
      enemyPlans.forEach((item, index) => {
        item.y++
        // 撞到了
        if(hitTestObject(planeInfo, item)) {
          ctx.emit('changePage', 'StartPage')
        }
        if(item.y >= screenHeight) {
          enemyPlans.splice(index, 1)
        }
      })
      // 我方子弹
      bullets.forEach((bullet, bulletIndex) => {
        bullet.y -= bulletSpeed
        enemyPlans.forEach((enemyPlan, enemyIndex) => {
          if(hitTestObject(enemyPlan, bullet)) {
            bullets.splice(bulletIndex, 1)
            enemyPlans.splice(enemyIndex, 1)
            integralNum.value++
          }
        })
        if(bullet.y < 0) {
          bullets.splice(bulletIndex, 1)
        }
        console.log(bullet.y)
      })
    }
    onMounted(() => {
      game.ticker.add(handleTicker)
    })
    onUnmounted(() => {
      game.ticker.remove(handleTicker)
    })
    return {
      planeInfo,
      enemyPlans,
      bullets,
      integralNum
    }
  },
  render(ctx) {
    // 创建敌机
    const createEnemyPlans = () => {
      return ctx.enemyPlans.map(item => {
        return h(Enemy, { enemyInfo: item })
      })
    }
    // 创建子弹
    const createBullets = () => {
      return ctx.bullets.map(item => {
        return h(Bullet, { bulletInfo: item })
      })
    }
    return h('Container', [
      h(Map, {integralNum: ctx.integralNum }), 
      h(Plane, { planInfo: ctx.planeInfo }),
      h(Integral, { integralNum: ctx.integralNum}),
      ...createEnemyPlans(),
      ...createBullets()
    ])
  }
})
